package com.winsdom.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.winsdom.mapper.BillingDetailMapper;
import com.winsdom.mapper.BillsMapper;
import com.winsdom.mapper.PaymentReceiptMapper;
import com.winsdom.service.PaymentService;
import com.winsdom.utils.PayUtil;
import com.winsdom.vo.uniformCharge.ChargeRequestDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/api/alipay")
@Api(tags = "支付宝支付接口")
@Slf4j
public class AliPayController {
    @Autowired
    private PayUtil payUtil;
    @Autowired
    private PaymentReceiptMapper paymentReceiptMapper;
    @Autowired
    private BillingDetailMapper billingDetailMapper;
    @Autowired
    private BillsMapper billsMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private PaymentService paymentService;

    /**
     * 支付宝支付成功回调（GET请求）
     * 注意：需在PayUtil中配置RETURN_URL为该接口路径
     */
    @GetMapping("/toSuccess")
    @ApiOperation("支付宝支付成功回调")
    @Transactional
    public String handleAlipayCallback(@RequestParam("out_trade_no") String outTradeNo) {
        log.info("接收到支付宝回调，订单号：{}", outTradeNo);

        try {
            // 从Redis获取ChargeRequestDTO
            String chargeRequestJson = stringRedisTemplate.opsForValue().get(outTradeNo);
            if (chargeRequestJson == null) {
                log.error("未找到ChargeRequestDTO信息，订单号：{}", outTradeNo);
                return "账单信息有误";
            }

            ChargeRequestDTO chargeRequestDTO = objectMapper.readValue(chargeRequestJson, ChargeRequestDTO.class);

            // 根据支付方式处理
            if (chargeRequestDTO.getPaymentMethod() == 4) { // 支付宝支付
                paymentService.handlePaymentSuccess(outTradeNo, chargeRequestDTO);
            } else if (chargeRequestDTO.getPaymentMethod() == 5) { // 临时收费
                paymentService.handleTemporaryPayment(outTradeNo, chargeRequestDTO);
            } else {
                log.error("不支持的支付方式：{}", chargeRequestDTO.getPaymentMethod());
                return "支付方式不支持";
            }

            // 从Redis中删除ChargeRequestDTO信息
            stringRedisTemplate.delete(outTradeNo);

            // 跳转成功页面
            return "redirect:http://localhost:8080/charge/success";

        } catch (Exception e) {
            log.error("回调处理失败，订单号：{}，错误：{}", outTradeNo, e.getMessage(), e);
            return "支付处理失败";
        }
    }


    @PostMapping("/notify") // 异步通知接口（POST）
    public String handleAlipayNotify(@RequestParam Map<String, String> params) {
        // 验签并处理异步通知
        return "123";
    }
}
